import axios from "axios";
import md5 from "js-md5";
import router from "@/router";
import store from "@/store";
import utils from "@/common/utils";
import {ElMessage, ElMessageBox, ElLoading} from "element-plus";
import ajax from '../../public/JavaScript/api/ajax.js'
import defaultSettings from "@/settings";

axios.defaults.headers["content-type"] = "application/x-www-form-urlencoded";

// 创建一个自定义的Axios对象
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    // baseURL: "http://192.168.0.19:9006",
    // baseURL: "http://192.168.0.19:9008",
    // baseURL: "http://192.168.0.19:9009",
    baseURL: ajax.url,
    // baseURL: "http://140.210.204.180:8888",

    // baseURL: "/backend",  // 华为云
    //   超时  单位ms
    timeout: 240000,

    /*这个配置很重要，允许axios携带用户Cookie到后端，不设置这个的话
      Set-Cookie是无效的,除此之外,Chrome默认开启了SameSite检查，如果
      后端不主动设置SameSite = none,Set-Cookie是无效的。详情请文章末尾
      参考阮老师的SameSite讲解*/
    //   withCredentials: true,
});

// 请求拦截
const base64 = require("js-base64").Base64;
let loading = null;

//请求拦截##############
service.interceptors.request.use(
    (config) => {
        loading = ElLoading.service({
          lock: true,
          text: '请求加载中，请稍等...',
          background: 'rgba(0, 0, 0, 0.7)',
        });
        if (!defaultSettings.tokenUrls.some((p) => p === config.url)) {
            const hasToken = store.getters.token;
            if (store.getters.islogin !== true || utils.isEmpty(hasToken))
                throw new Error("Invalid_Token_CurrentSys");
            else {
                config.headers["Token"] = hasToken;
                config.headers["Authorization"] = `Bearer ${hasToken}`;
            }
        } else
            config.headers["Authorization"] = `Basic ${base64.encode(
                `${defaultSettings.clientID}:${defaultSettings.clientSecret}`
            )}`;
        const time = Math.round(new Date().getTime() / 1000);
        const random = Math.round(Math.random() * 1000000);
        const sig = md5(`${time}${random}`);
        config.headers["Sig"] = sig;
        config.headers["Time"] = time;
        config.headers["Random"] = random;
        return config;
    }
    // async error => {
    //   console.log("request error：", error); // for debug
    //   if (error.message === 'Invalid_Token_CurrentSys') {
    //     await redirectFunc();
    //     if (error.message === 'Invalid_Token_CurrentSys') error.message = "Token已失效";
    //   }
    //   return Promise.reject(new Error(error.message || '请求出错'));
    // }
);

//响应拦截************************
service.interceptors.response.use(
    async (response) => {
    loading.close();
        const res = response.data;
        // console.log('res',res);
        if (response.status !== 200 || (res.code && res.code !== 200)) {
            if (res && res.code === 401) await redirectFunc();
            if (res.code === 400) {
                ElMessage.error(res.msg);
            }
            return Promise.reject(new Error(res.msg || "请求未响应"));
        } else {
            loading.close();
            if (res.code) {
                return res.data;
            } else {
                return response.data;
            }
        }

    },
    async (error) => {
        // console.log("response error：", error); // for debug
        loading.close();
        if (
            error.message === "Invalid_Token_CurrentSys" ||
            (error.response && error.response.data && error.response.data.code) ===
            401
        ) {
            await redirectFunc();
            if (error.message === "Invalid_Token_CurrentSys")
                error.message = "Token已失效";
        }
        return Promise.reject(
            new Error(
                (error.response && error.response.data && error.response.data.msg) ||
                error.message ||
                "请求未响应"
            )
        );
    }
);

const redirectFunc = async () => {
    await ElMessageBox.confirm("您的凭证已失效，请重新登录", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showCancelButton: false,
        type: "warning",
    })
        .then(async () => {
            const urlPath = router.currentRoute.value.path || "";
            await store.dispatch("system/resetToken").then(() => {
                if (urlPath === "/login") router.replace({path: "/login"});
                else router.replace({path: "/login", query: {redirect: urlPath}});
            });
        })
        .catch(() => {
        });
};

//暴露Axios实例化对象，允许所有文件调用Axios
export default service;
